<?php


namespace app\api\model;


use ApiOper;
use app\common\library\aliyunsms\alidayu;
use app\common\library\IDMan;
use app\common\model\BaseModel;
use common;

class UserRideViolationOrderModel extends BaseModel
{
    protected $name = 'user_ride_violation_order';
    protected $pk = 'id';
    function submit($bike_info, $violation_type, $violation_desc, $violation_remark, $images)
    {
        $city_id = $bike_info['city_id'];
        $bike_id = $bike_info['id'];

        $oper_info = ApiOper::instance()->userinfo();
        $userinfo = (new UserModel())->query_info($bike_info['last_order_oper_id']);


        $order_info = (new UserRadingOrderModel())->query_info_by_city_id($city_id, $bike_info['last_order_id']);
        if (empty($order_info)) {
            $this->throw_myexception(X_ERROR, "查询最近订单失败!");
        }

        if ($order_info['is_violational']) {
            $this->throw_myexception(X_ERROR, "违章已举报!");
        }

        if ($order_info['violation_fine'] > 0 && $order_info['violation_blacklisted'] > 0) {
            $this->throw_myexception(X_ERROR, "无法举报，违章已举报!");
        }

        $distance = common::distance($order_info['end_coordinate'], $bike_info['coordinate']);
        if ($distance > 10) {
            //throw_myexception(X_ERROR, "车辆当前位置非用户停车位置!");
        }

        (new UserRadingOrderModel())->set_violational($order_info['city_id'], $order_info['id']);

        $info = [
            'id' => IDMan::city_order_id($city_id),
            'city_id' => $city_id,
            'bike_id' => $bike_id,
            'bike_sn' => $bike_info['sn'],
            'order_state' => USER_RIDE_VIOLATION_ORDER_STATE_REPORT,
            'reporter_type' => $oper_info['user_type'],
            'reporter_id' => $oper_info['id'],
            'reporter_name' => $oper_info['name'],
            'reporter_phone' => $oper_info['phone'],
            'create_time' => date('Y-m-d H:i:s'),
            'violator_id' => $bike_info['last_order_oper_id'],
            'violator_name' => $bike_info['last_order_oper_name'],
            'violator_phone' => $bike_info['last_order_oper_phone'],
            'violation_type' => $violation_type,
            'violation_remark' => $violation_remark,
            'violation_desc' => $violation_desc,
            'violation_count' => $userinfo['violation_count'] + 1,
            'imgs' => $images,
            'bound_order_id' => $order_info['id'],
        ];

        if (!empty($bike_info)) {
            $info['health_state'] = $bike_info['health_state'];
            $info['is_wheel_locked'] = $bike_info['is_wheel_locked'];
            $info['battery_level'] = $bike_info['battery_level'];
            $info['battery_capacity'] = $bike_info['battery_capacity'];
            $info['battery_volt'] = $bike_info['battery_volt'];
            $info['is_acc_on'] = $bike_info['is_acc_on'];
            $info['is_battery_locked'] = $bike_info['is_battery_locked'];
            $info['is_under_volt'] = $bike_info['is_under_volt'];
            $info['coordinate'] = $bike_info['coordinate'];
            $info['park_coordinate'] = $bike_info['park_coordinate'];
            $info['address'] = $bike_info['address'];
        }

        self::create($info);


        return $info;
    }

    function punish($city_id, $order_id, $fine, $blacklist)
    {
        $order_info = $this->query_info($city_id, $order_id);
        if (empty($order_info)) {
            $this->throw_myexception(ERROR_QUERY_INFO, "query bike info error");
        }
        if ($order_info['order_state'] != USER_RIDE_VIOLATION_ORDER_STATE_REPORT) {
            $this->throw_myexception(ERROR_STATE_DISMATCH, "order state = {$order_info['order_state']}");
        }

        $oper_info = ApiOper::instance()->userinfo();
        $userinfo = (new UserModel())->query_info($order_info['violator_id']);

        $need_audit = false;
        if ($blacklist > 0) {
            $need_audit = true;
        }

        $data = [
            'order_state' => $need_audit ? USER_RIDE_VIOLATION_ORDER_STATE_PINISH : USER_RIDE_VIOLATION_ORDER_STATE_FINISH,
            'punisher_id' => $oper_info['id'],
            'punisher_name' => $oper_info['name'],
            'punisher_phone' => $oper_info['name'],
            'punish_time' => date('Y-m-d H:i:s'),
            'fine' => $fine,
            'blacklisted' => $blacklist,
        ];

        $where = [
            'city_id' => $city_id,
            'id' => $order_id,
        ];

        self::update($data, $where);
        if (!$need_audit && $fine > 0) {
            (new UserModel())->ride_violation_punish($userinfo['id'], $fine, $blacklist);
            (new UserRadingOrderModel())->set_violation_find_blacklist($order_info['city_id'], $order_info['bound_order_id'], $fine, $blacklist);
            (new PayModel())->add_record($city_id, $order_info['violator_id'], ORDER_TYPE_RIDE_VOILATION_FINE, $order_id, PAY_GATEWAY_WALLET, $fine);
            (new alidayu())->send_sms_user_ride_violation($userinfo['phone']);
        }

    }

    function audit($city_id, $order_id, $agree)
    {
        $order_info = $this->query_info($city_id, $order_id);
        if (empty($order_info)) {
            $this->throw_myexception(ERROR_QUERY_INFO, "query bike info error");
        }
        if ($order_info['order_state'] != USER_RIDE_VIOLATION_ORDER_STATE_PINISH) {
            $this->throw_myexception(ERROR_STATE_DISMATCH, "order state = {$order_info['order_state']}");
        }

        $userinfo = (new UserModel())->query_info($order_info['violator_id']);

        $data = [
            'order_state' => $agree ? USER_RIDE_VIOLATION_ORDER_STATE_FINISH : USER_RIDE_VIOLATION_ORDER_STATE_REVOKE,
        ];

        $where = [
            'city_id' => $city_id,
            'id' => $order_id,
        ];

        self::update($data, $where);
        if ($agree) {
            $fine = $order_info['fine'];
            $blacklist = $order_info['blacklisted'];
            if ($fine > 0 || $blacklist > 0) {
                (new UserModel())->ride_violation_punish($userinfo['id'], $fine, $blacklist);
            }
            (new UserRadingOrderModel())->set_violation_find_blacklist($order_info['city_id'], $order_info['bound_order_id'], $fine, $blacklist);

            if ($fine > 0) {
                (new PayModel())->add_record($city_id, $order_info['violator_id'], ORDER_TYPE_RIDE_VOILATION_FINE, $order_id, PAY_GATEWAY_WALLET, $fine);
            }
            (new alidayu())->send_sms_user_ride_violation($userinfo['phone']);
        }

    }

    function query_list($city_id, $condition, $pos, $limit)
    {
        $sfs = array_keys($this->paramlist);
        $beans = [];
        $st ="1=1";
        if ($city_id) {
            $st = $st . " and city_id = ?";
            $beans[] = $city_id;
        }
        if (isset($condition['user_id'])) {
            $st = $st . " and violator_id = ?";
            $beans[] = $condition['user_id'];
        }
        if (isset($condition['order_state'])) {
            $st = $st . " and order_state = ?";
            $beans[] = $condition['order_state'];
        }
        if (isset($condition['violation_type'])) {
            $st = $st . " and violation_type = ?";
            $beans[] = $condition['violation_type'];
        }
        if (isset($condition['punish_type'])) {
            if ($condition['punish_type'] == 0) {

            } else if ($condition['punish_type'] == 1) {
                $st = $st . " and fine > 0 and blacklisted = 0";
            } else if ($condition['punish_type'] == 2) {
                $st = $st . " and fine = 0 and blacklisted = 1";
            } else if ($condition['punish_type'] == 3) {
                $st = $st . " and fine > 0 and blacklisted = 1";
            }
        }

        if (!empty($condition['sk'])) {
            $sk = $condition['sk'];
            if (common::is_name($sk)) {
                $st = $st . " and (violator_name = ? or reporter_name = ? )";
                $beans[] = $sk;
                $beans[] = $sk;
            } else if (common::is_phone($sk)) {
                $st = $st . " and violator_phone = ?";
                $beans[] = $sk;
            } else if (IDMan::is_bike_id($sk)) {
                $st = $st . " and bike_id = ?";
                $beans[] = $sk;
            } else if (IDMan::is_bike_sn($sk)) {
                $st = $st . " and bike_sn = ?";
                $beans[] = $sk;
            } else if (IDMan::is_city_order_id($sk)) {
                $st = $st . " and id = ?";
                $beans[] = $sk;
            } else {
                return [];
            }
        }
        if (isset($condition['user_id'])) {
            $st = $st . " and violator_id = ?";
            $beans[] = $condition['user_id'];
        }

        if (isset($cd['start_time'])) {
            $st = $st . " and create_time >= ? ";
            $beans[] = $condition['start_time'];
        }
        if (isset($cd['end_time'])) {
            $st = $st . " and create_time <= ? ";
            $beans[] = $condition['end_time'];
        }


        $st = $st . " order by create_time desc limit $pos, $limit";
        $rows = $this->whereRaw($st,$beans)->select();
        if ($rows->isEmpty()) {
            return null;
        }
        $l = [];
        foreach ($rows as $row) {
            $l[] = common::sql_row($this->paramlist, $row);
        }
        return $l;
    }

    function query_info($city_id, $order_id)
    {
        $sfs = array_keys($this->paramlist);
        $beans = [
            'city_id'=>$city_id,
            'id'=>$order_id];

        $info = $this->where($beans)->field($sfs)->find();
        return $info;
    }


    function revoke($city_id, $order_id)
    {
        $order_info = $this->query_info($city_id, $order_id);
        if (empty($order_info)) {
            $this->throw_myexception(ERROR_QUERY_INFO, "query bike info error");
        }
        if ($order_info['order_state'] != USER_RIDE_VIOLATION_ORDER_STATE_FINISH) {
            $this->throw_myexception(ERROR_STATE_DISMATCH, "订单状态不匹配,请重试");
        }

        $oper_info = ApiOper::instance()->userinfo();
        $userinfo = (new UserModel())->query_info($order_info['violator_id']);

        $data = [
            'order_state' => USER_RIDE_VIOLATION_ORDER_STATE_REVOKE,
            'revoke_oper_id' => $oper_info['id'],
            'revoke_oper_name' => $oper_info['name'],
            'revoke_time' => date('Y-m-d H:i:s'),
        ];

        $where = [
            'city_id' => $city_id,
            'id' => $order_id,
        ];

        self::update($data, $where);

        if ($order_info['fine'] > 0 || $order_info['blacklisted'] > 0) {
            (new UserModel())->ride_violation_revoke($userinfo['id'], $order_info['fine'], $order_info['blacklisted']);
        }


        if ($order_info['fine'] > 0) {
            (new PayModel())->add_record($city_id, $order_info['violator_id'], ORDER_TYPE_RIDE_VOILATION_FINE_REVOKE, $order_id, PAY_GATEWAY_WALLET, 0 - $order_info['fine']);
        }
    }

    //分析
    function analyze($city_id,$condition){
        $list = $this->query_list($city_id,$condition,0,5000);

        $violation_list =[];
        if (is_array($list)){
            foreach ($list as $val){
                if (!isset($violation_list[$val['reporter_id']])){
                    $violation_list[$val['reporter_id']] = 1;
                }
                else
                    $violation_list[$val['reporter_id']]++;
            }

        }

        return $violation_list;
    }
}